﻿using Stardust.Client;
using Stardust.Common.Enum;
using Stardust.Common.Utils;
using Stardust.ConfigCenterWeb.Code.Entities;
using Stardust.ConfigCenterWeb.Code.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Stardust.ConfigCenterWeb.Controllers
{
    public class ServiceNodeController : Controller
    {
        // GET: ServiceNode
        public ActionResult Index(string serviceName, string address, string version, ServerNodeStatus? status)
        {
            var list = ServerNodeService.Instance.SearchList(serviceName, address, version, status);
            return View(list);
        }


        public ActionResult EditAsync(ServerNode model)
        {
            ServerNodeService.Instance.Edit(model);
            return new EmptyResult();
        }

        public ActionResult DeleteAsync(long nodeId, string serviceName)
        {
            ServerNodeService.Instance.Delete(nodeId, serviceName);
            return new EmptyResult();
        }

        public ActionResult ContractList(long nodeId)
        {
            var node = ServerNodeService.Instance.GetOne(nodeId);
            if (node == null)
            {
                return Content("服务节点不存在");
            }

            var contractList = ServiceContractService.Instance.GetContractsByNode(nodeId);
            ViewBag.node = node;
            ViewBag.contractList = contractList;

            return View();
        }

        [HttpPost]
        public ActionResult Invoke(string serviceName, string version, string controllerName, string actionName, string jsonParams)
        {
            try
            {
                StardustClient client = new StardustClient(serviceName, version);
                var result = client.Invoke<string>(controllerName, actionName, jsonParams);
                var indentJson = SerializerHelper.IndentJson(result);
                return Content(indentJson);
            }
            catch (Exception exp)
            {
                return Content(exp.Message + Environment.NewLine + exp.StackTrace);
            }
        }
    }
}